package shooter.xml;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import shooter.Einstellungen;

/**
 * The XML handler of this project.
 * 
 * @author Michail Tausch
 */
public class Xmlschreiber {
	static String name = "";
	
	/**
	 * Returns the name of the player
	 */
	public static String getPlayerName() {
		try {
			DocumentBuilder db =
				DocumentBuilderFactory.newInstance().newDocumentBuilder();
			// XML Parsen
			Document parse =
				db.parse(Xmlschreiber.class.getClassLoader()
						.getResourceAsStream(
								Einstellungen.getXMLPath() + "Profil.xml"));
			// Elemente Erster Ebene
			XPath xpath = XPathFactory.newInstance().newXPath();
			String expression = "/profil/name";
			Node widgetNode =
				(Node) xpath.evaluate(expression, parse,
						XPathConstants.NODE);
			if (widgetNode != null) {
				name = widgetNode.getTextContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return name;
	}
	
	/**
	 * Sets the name of the player.
	 * @param name
	 */
	public static void setPlayerName(String name) {
		try {
			DocumentBuilder db =
				DocumentBuilderFactory.newInstance().newDocumentBuilder();
			// XML Parsen
			Document parse =
				db.parse(Xmlschreiber.class.getClassLoader()
						.getResourceAsStream(
								Einstellungen.getXMLPath() + "Profil.xml"));
			XPath xpath = XPathFactory.newInstance().newXPath();
			String expression = "/profil/name";
			Node widgetNode =
				(Node) xpath.evaluate(expression, parse,
						XPathConstants.NODE);
			if (widgetNode != null) {
				widgetNode.setTextContent(name);
			}
			// Dokument wieder wegschreiben.
			TransformerFactory transformerFactory =
				TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(parse);
			StreamResult result =
				new StreamResult(new FileOutputStream(new File(
						Xmlschreiber.class.getClassLoader().getResource(
								Einstellungen.getXMLPath() + "Profil.xml")
								.toURI())));
			transformer.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}